
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, message, Tag } from 'antd';
import React from 'react';
import GameCreateForm from './components/GameCreateForm';
import GameEditForm from './components/GameEditForm';
import GameEditRulesForm from './components/GameEditRulesForm';
import GameEditRulesCommForm from './components/GameEditRulesCommForm';
import GameInfoView from '@/components/GameInfo/GameInfoView';
import services from '@/services/game';
import { GameItem } from '@/services/game/GameController';
const { queryPageGame, deleteItem, updateStateItem } = services.GameController;

/**
 *  删除
 * @param selectedRows
 */
const handleRemove = async (selectedRow: GameItem) => {
  ////1-报名中  2-进行中 3-已结束 4已取消
  if (selectedRow.type !== 4) {
    message.error('已取消的赛事,才可以删除！');
    return;
  }
  const hide = message.loading('正在删除');
  try {
    await deleteItem(selectedRow.gameId);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 *  更新状态
 * @param selectedRows
 */
const handleUpdate = async (selectedRow: GameItem, newStatus: number) => {
  //1-报名中  2-进行中 3-已结束 4已取消
  if (selectedRow.status === newStatus) {
    message.error('请选择不同的状态！');
    return;
  }
  if (selectedRow.status === 3) {
    message.error('已结束的赛事,不可以修改状态！');
    return;
  }
  const hide = message.loading('正在更新状态...');
  try {
    await updateStateItem(selectedRow.id, newStatus);
    hide();
    message.success('更新状态成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('更新状态失败，请重试');
    return false;
  }
};

const GamesPage: React.FC = () => {
  const actionRef = React.useRef<ActionType>();
  const [row, setRow] = React.useState<GameItem>();

  //新建赛事
  const [createModalVisible, handleModalVisible] =
    React.useState<boolean>(false);
  //查看赛事
  const [lookModalVisible, setLookModalVisible] =
    React.useState<boolean>(false);
  //编辑赛事
  const [editModalVisible, setEditModalVisible] =
    React.useState<boolean>(false);
  //通用规则
  const [editCommModalVisible, setEdittCommModalVisible] =
    React.useState<boolean>(false);
  //赛制设置
  const [editRulesModalVisible, setEdittRulesModalVisible] =
    React.useState<boolean>(false);

  const columns: ProColumns<GameItem>[] = [
    {
      title: '宣传图',
      dataIndex: 'url',
      valueType: 'image',
      hideInSearch: true,
    },
    {
      title: '赛事',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        1: { text: '报名中' },
        2: { text: '进行中' },
        3: { text: '已结束' },
        4: { text: '已取消' },
      },
      renderText: (text: any) => {
        return (
          <Tag
            color={
              text === 1
                ? 'green'
                : text === 2
                  ? 'blue'
                  : text === 3
                    ? 'red'
                    : 'gray'
            }
          >
            {text === 1
              ? '报名中'
              : text === 2
                ? '进行中'
                : text === 3
                  ? '已结束'
                  : '已取消'}
          </Tag>
        );
      },
    },
    {
      title: '报名人数',
      dataIndex: 'offSize',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '人数限制',
      dataIndex: 'allSize',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '赛制',
      dataIndex: 'type',
      hideInForm: true,
      valueEnum: {
        1: { text: '积分晋级赛' },
        2: { text: '积分赛' },
      },
    },
    {
      title: '报名截止时间',
      dataIndex: 'offTime',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '开赛时间',
      dataIndex: 'startTime',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      valueType: 'text',
      hideInSearch: true,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setRow(record);
              setEditModalVisible(true);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleUpdate(record, 4);
            }}
          >
            取消
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setRow(record);
              setLookModalVisible(true);
            }}
          >
            查看
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleUpdate(record, 1);
            }}
          >
            发布
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleRemove(record);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      ghost
      header={{
        title: '赛事管理',
      }}
    >
      <ProTable<GameItem>
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => handleModalVisible(true)}
          >
            新增赛事
          </Button>,
          <Button
            key="1"
            type="primary"
            onClick={() => setEdittRulesModalVisible(true)}
          >
            赛制规则
          </Button>,
          <Button
            key="1"
            type="primary"
            onClick={() => setEdittCommModalVisible(true)}
          >
            通用规则
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const { data, success } = await queryPageGame({
            ...params,
            sorter,
            filter,
          });
          return {
            data: data?.list || [],
            success,
          };
        }}
        columns={columns}
      />

      {/* 查看赛事 */}
      {lookModalVisible && <GameInfoView
        gameId={row?.gameId ?? ''}
        modalVisible={lookModalVisible}
        onCancel={setLookModalVisible}
      />}
      {/* 编辑赛事 */}
      {editModalVisible && <GameEditForm
        gameId={row?.gameId ?? ''}
        modalVisible={editModalVisible}
        onCancel={setEditModalVisible}
        onReloadAndRest={() => {
          actionRef?.current?.reloadAndRest?.();
        }}
      />}
      {/* 新增赛事 */}
      {createModalVisible && <GameCreateForm
        modalVisible={createModalVisible}
        onCancel={handleModalVisible}
        onReloadAndRest={() => {
          actionRef?.current?.reloadAndRest?.();
        }}
      />}
      {/* 赛制设置 */}
      {editRulesModalVisible && <GameEditRulesForm
        modalVisible={editRulesModalVisible}
        onCancel={setEdittRulesModalVisible}
      />}
      {/* 通用规则 */}
      {editCommModalVisible && <GameEditRulesCommForm
        modalVisible={editCommModalVisible}
        onCancel={setEdittCommModalVisible}
      />}
    </PageContainer>
  );
};

export default GamesPage;
